package com.standardoperationapp.activity;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.standardoperationapp.R;
import com.standardoperationapp.adapter.ApplyListAdapter;
import com.standardoperationapp.adapter.EmergyListAdapter;
import com.standardoperationapp.bean.CheckLockEmpowerBean;
import com.standardoperationapp.bean.CheckUnLockNumBean;
import com.standardoperationapp.bean.CilckEventBean;
import com.standardoperationapp.bean.MyAcessDoorBean;
import com.standardoperationapp.bluetooth.BluetoothManger;
import com.standardoperationapp.global.GlobalVaries;
import com.standardoperationapp.global.GsonUtils;
import com.standardoperationapp.net.BaseSubscribe;
import com.standardoperationapp.net.OnSuccessAndFaultListener;
import com.standardoperationapp.net.OnSuccessAndFaultSub;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class EmergencyDoorActivity extends AppCompatActivity {

    private ListView listView;
private EmergyListAdapter emergyListAdapter;
    private android.app.AlertDialog.Builder alertBuilder;
    private android.app.AlertDialog alertDialog;
    private TextView batteryTv, warnTv;
    private ProgressDialog progressDialog;

    private boolean ConnectCounterFlag=false;
    private int  ConnectCounter=0;
    private String opentoken="";
    private String openresaon="";
private List<MyAcessDoorBean.DataBean > list = new ArrayList<MyAcessDoorBean.DataBean>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_emergency_door);
        GlobalVaries.curBlueMac="";
        initListView();
        getMyAcessDoor();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }
    @Subscribe(sticky = true,threadMode = ThreadMode.MAIN)
    public void getEventBus(CilckEventBean event){
        Log.e("TAG","------------"+event.getPosition()+" "+event.getType());
        // curSelectIndex=event.getPosition();
        // type =event.getType();
        if(event.getType()==2){
            showAlertDialog(event.getPosition());
        }

    }

    @Override
    public void onDestroy() {

        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void getMyAcessDoor(){

        BaseSubscribe.getMyAccessDoor(EmergencyDoorActivity.this, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
            @Override
            public void onSuccess(Object result) {
                MyAcessDoorBean myAcessDoorBean = GsonUtils.fromJson(result.toString(), MyAcessDoorBean.class);
                if(myAcessDoorBean==null){
                    Toast.makeText(EmergencyDoorActivity.this, "后台发送通道锁列表为空！" , Toast.LENGTH_LONG).show();

                    return;
                }
                for (int i = 0; i < myAcessDoorBean.getData().size(); i++) {
                    MyAcessDoorBean.DataBean dataItem = myAcessDoorBean.getData().get(i);
                    if(dataItem==null){
                        continue;
                    }
                    list.add(dataItem);

                }
                if (emergyListAdapter == null) {
                    emergyListAdapter = new EmergyListAdapter(EmergencyDoorActivity.this, list);
                    listView.setAdapter(emergyListAdapter);
                } else {
                    emergyListAdapter.upDta(list);
                    emergyListAdapter.notifyDataSetChanged();
                }

            }

            @Override
            public void onFault(String errorMsg) {
                Toast.makeText(EmergencyDoorActivity.this, "获取通道锁列表失败！" + errorMsg, Toast.LENGTH_LONG).show();
            }

        }));


    }

    private void initListView()
    {
        listView=(ListView)findViewById(R.id.emergy_listview) ;

        //添加表头
        View headerView = LayoutInflater.from(this).inflate(R.layout.emergy_listview_item, listView, false);
        listView.addHeaderView(headerView);
        TextView tx1= headerView.findViewById(R.id.emergy_tx1);
        tx1.setText("序号");
        tx1= headerView.findViewById(R.id.emergy_tx2);
        tx1.setText("通道门");
        tx1= headerView.findViewById(R.id.emergy_tx3);
        tx1.setText("操作");

    }
    String idstr="";
    public void showAlertDialog(int position){


        MyAcessDoorBean.DataBean item= (MyAcessDoorBean.DataBean)emergyListAdapter.getItem(position);
        if(item!=null)
        {
            idstr=Integer.toString(item.getLockId());
            Log.e("syj", item.getDoorName());
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(EmergencyDoorActivity.this);
        builder.setTitle("请填写开锁原因");

        LinearLayout layout = new LinearLayout(EmergencyDoorActivity.this);
        layout.setOrientation(LinearLayout.VERTICAL);
        TextView tx = new TextView(EmergencyDoorActivity.this);
        tx.setText("(请向调度中心索要紧急开锁密钥！)");
        tx.setTextColor(Color.RED);
        layout.addView(tx);
        EditText editText1 = new EditText(EmergencyDoorActivity.this);
        editText1.setHint("开锁密钥");
        layout.addView(editText1);

        EditText editText2 = new EditText(EmergencyDoorActivity.this);
        editText2.setHint("开锁原因");
        layout.addView(editText2);

        builder.setView(layout);

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String openkey = editText1.getText().toString();
                openresaon=editText2.getText().toString();

               if(openkey.isEmpty()||openresaon.isEmpty())
               {
                   Toast.makeText(EmergencyDoorActivity.this,"密钥和原因不能为空！",Toast.LENGTH_LONG).show();
                   return;
               }
                GlobalVaries.curBlueMac=item.getMacAddress();
                Toast.makeText(EmergencyDoorActivity.this,"当前蓝牙锁："+GlobalVaries.curBlueMac,Toast.LENGTH_LONG).show();
                chekUnlockNum(idstr,openkey,openresaon);
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        AlertDialog dialog = builder.create();
        dialog.show();
    }
    //校验紧急开锁码
    public void chekUnlockNum(String id,String randomNumber,String reason){
        BaseSubscribe.chekUnlockNum(EmergencyDoorActivity.this,id,randomNumber,new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
            @Override
            public void onSuccess(Object result) {
                CheckUnLockNumBean bean =GsonUtils.fromJson(result.toString(), CheckUnLockNumBean.class);
                ConnectCounterFlag=true;
                ConnectCounter =0;
                if(bean!=null)
                {
                    opentoken =bean.getData();
                }

                startBluetooth();
              //  sendEmergyOpenRecord(bean.getData(),reason);
            }

            @Override
            public void onFault(String errorMsg) {
                Toast.makeText(EmergencyDoorActivity.this, "发送紧急开门码失败！" + errorMsg, Toast.LENGTH_LONG).show();
            }

        }));
    }
    public void sendEmergyOpenRecord(String token,String reason)
    {
        HashMap<String,String>hashMap = new HashMap<String,String>();
        hashMap.put("battery", Integer.toString(GlobalVaries.curBattery.intValue()));
        hashMap.put("openTime",GlobalVaries.openTime);
        hashMap.put("closeTime",GlobalVaries.closeTime);
        hashMap.put("reason",reason);
       // Toast.makeText(EmergencyDoorActivity.this, "当前发送的电量为" + Integer.toString(GlobalVaries.curBattery.intValue()), Toast.LENGTH_LONG).show();

        BaseSubscribe.getEmergentLockOpen(EmergencyDoorActivity.this,token,hashMap,new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
            @Override
            public void onSuccess(Object result) {
//
                Toast.makeText(EmergencyDoorActivity.this, "发送紧急开门记录成功！", Toast.LENGTH_LONG).show();

            }

            @Override
            public void onFault(String errorMsg) {
                Toast.makeText(EmergencyDoorActivity.this, "发送紧急开门记录失败！" + errorMsg, Toast.LENGTH_LONG).show();
            }

        }));
    }
    public void startBluetooth() {


        BluetoothManger.blueHandler =handler;

        BluetoothManger.initBluetooth(EmergencyDoorActivity.this,handler,ConnectCounter);
        BluetoothManger.initPermission(EmergencyDoorActivity.this);
        boolean bluetoothLEAvailable = getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);
        //   GlobalVaries.curBlueMac="D0:ED:2B:46:A2:B9";
        alertBuilder = null;
        if (bluetoothLEAvailable) {
            //   GlobalVaries.curBlueMac="FB:35:D2:63:BF:0B";
            BluetoothManger.connectLock(EmergencyDoorActivity.this,handler, GlobalVaries.curBlueMac, false);
            startShowProgressDialog("正在连接蓝牙设备！");
            ConnectCounterFlag = true;
            if(BluetoothManger.reconnectFlag==false) {
                ConnectThread connectThread = new ConnectThread();
                new Thread(connectThread).start();
            }
        }
    }
    private void startShowProgressDialog(String msg) {
        Log.e("syj","startShowProgressDialog");
        if (progressDialog == null) {
            Log.e("syj","null");
            progressDialog = new ProgressDialog(EmergencyDoorActivity.this);

            progressDialog.setTitle("提示");//设置对话框显示的内容

            progressDialog.setMessage(msg);//设置不能用“取消”按钮关闭

            progressDialog.setCancelable(false);//设置对话框的进度条风格

            progressDialog.show();

        } else {
            progressDialog.setMessage(msg);
        }


    }

    public void dismissprogressDialog() {
        Log.e("syj","dismissdialog");
        progressDialog.dismiss();
        progressDialog=null;
    }
    public void showWarnDialog(String lefttime, Double battery) {
        if (GlobalVaries.UpdateWarnFlag == false)
        {
            Log.e("syj","updateFlag false");
            return;
        }

        if (alertBuilder == null) {
            alertBuilder = new android.app.AlertDialog.Builder(this);
            final View view = getLayoutInflater().inflate(R.layout.activity_door_warn, null);

            warnTv = (TextView) view.findViewById(R.id.warn_closewarn_tx);
            warnTv.setText("关锁提醒：" + lefttime);
            batteryTv = (TextView) view.findViewById(R.id.warn_battery_tx);
            Log.e("syj","update3:"+Double.toString(GlobalVaries.curBattery));

            batteryTv.setText("门锁剩余电量： " + Integer.toString(GlobalVaries.curBattery.intValue())+"%");
            Button closeBtn = (Button) view.findViewById(R.id.warn_close_Btn);
            closeBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(BluetoothManger.mLockIsOpened)
                    {
                        Toast.makeText(EmergencyDoorActivity.this, "请检查是否关锁！", Toast.LENGTH_LONG).show();
                        return ;
                    }else{
                        Toast.makeText(EmergencyDoorActivity.this, "关锁", Toast.LENGTH_LONG).show();
                        GlobalVaries.UpdateWarnFlag = false;
                        BluetoothManger.counter = 0;
                        BluetoothManger.disconnectLock();

                        alertDialog.dismiss();
                        alertBuilder = null;
                    }

                }
            });
            alertBuilder.setCancelable(false);
            alertBuilder.setView(view);
//    builder.setPositiveButton("关锁", new DialogInterface.OnClickListener() {
//        @Override
//        public void onClick(DialogInterface dialog, int which) {
//
//            dialog.cancel();
//        }
//    });
            alertDialog = alertBuilder.create();

            alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            alertDialog.show();
        } else {
            warnTv.setText("关锁提醒：" + lefttime);
            batteryTv.setText("门锁剩余电量： " + Integer.toString(battery.intValue())+"%");
        }
    }



    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            myhandleMessage(msg);
        }
    };

    //private boolean mneedreconnect =true;
    private void myhandleMessage(Message msg) {
        try {
            //syj     startCaptureTimeCount();
            Log.e("syj","msg is "+Integer.toString(msg.what));
            switch (msg.what) {
//GATT连接上
                case BluetoothManger.ACTION_GATT_CONNECTED:
                    //   mneedreconnect=false;
                    dismissprogressDialog();
                    Log.e("syj","update1:"+Double.toString(GlobalVaries.curBattery));
                    GlobalVaries.UpdateWarnFlag=true;
                    alertBuilder = null;
                    ConnectCounterFlag=false;
                    ConnectCounter =0;
                    BluetoothManger.reconnectFlag=false;
                    showWarnDialog(Integer.toString(BluetoothManger.counter),GlobalVaries.curBattery);
                    UpdateThread myThread = new UpdateThread();
                    new Thread(myThread).start();
                    break;
                //GATT断开连接
                case  BluetoothManger.ACTION_GATT_DISCONNECTED:
                    GlobalVaries.UpdateWarnFlag=false;
                    BluetoothManger.resetBluetooth();

                    if(BluetoothManger.reconnectFlag==false) {
                        dismissprogressDialog();
                        ConnectCounter = 0;
                        ConnectCounterFlag = false;
                        Log.e("syj","stop Aand not reconnect");
                    }
                    //根据实际需要 决定是否重连
                    Log.e( BluetoothManger.TAG, "Lock DisConnected." + hashCode());


                    break;

                case  BluetoothManger.ACTION_GATT_SERVICES_DISCOVERED: //发现了对应的服务
                    // Log.e(TAG,"Lock GATT_SERVICES_DISCOVERED."+hashCode());//add by 20221026
                    //发现服务..mWorkModel:0=开锁，1=查询参数，2=设置参数
                    if ( BluetoothManger.mWorkModel == 0) {
                        if ( BluetoothManger.mLockIsOpened ||  BluetoothManger.mIsDoCheckLockState)
                            handler.sendEmptyMessageDelayed(4, 500);//验封.检测锁状态
                        else
                            handler.sendEmptyMessageDelayed(0, 500);//解封，开锁
                    }


                    break;
                case  BluetoothManger.ACTION_BLE_REAL_DATA:
                    byte[]values =(byte[])msg.obj;
                    BluetoothManger.TMPL_processData(values);
                    Log.e(BluetoothManger.TAG,"state_changed");

                    break;
//                case BluetoothAdapter.ACTION_STATE_CHANGED:
//                    // Log.e(LockManageActivity.class.getSimpleName(),"state_changed");
//                    break;
                case 0://发送开锁指令
                    BluetoothManger.mIsDoCheckLockState = false;

                    BluetoothManger.TMPL_ReadLockUTCTime();

                    break;
                case BluetoothManger.DISMISS_PROGRESS_DIALOG:
//                    GlobalVaries.UpdateWarnFlag=false;
//                    BluetoothManger.resetBluetooth();
                    dismissprogressDialog();
                    break;
////                case 1://获取电量
//                    byte[] batteryBytes = {0x02, 0x01, 0x01, 0x01, token[0], token[1], token[2], token[3], 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
//                    boolean result = writeCharacteristic_GuaSuo(batteryBytes);
//                    Log.e(TAG, "Lock 发送获取电量指令=" + result);
//                    break;
////                case 2://开锁
//                   byte[] sendDataBytes = new byte[]{ 0x05, 0x01, 0x06,password[0], password[1], password[2], password[3], password[4], password[5], token[0], token[1], token[2], token[3], 0x00, 0x00, 0x00};
//                    result = writeCharacteristic_GuaSuo(sendDataBytes);
//                    Log.e(TAG, "Lock 发送开锁指令=" + result);
//                    break;
                case 3://获取锁状态

//                    byte[] sendDataBytes1 = new byte[]{0x05, 0x0E, 0x01, 0X01, token[0], token[1], token[2], token[3], 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
//                    result = writeCharacteristic_GuaSuo(sendDataBytes1);
                    Log.e(BluetoothManger.TAG, "Lock 发送获取锁状态指令=" );
                    break;
                case 4://发送施封指令。。航鸿达
                    BluetoothManger.TMPL_SendGetLockStateCMD();
                    Log.e( BluetoothManger.TAG, "Lock 发送获取锁状态指令,result=");
                    break;
                case  BluetoothManger.UPDATE_WARNDIALOG:
//                    BluetoothManger.TMPL_SendGetLockStateCMD();
//                    Log.e( BluetoothManger.TAG, "Lock 发送获取锁状态指令2,result=");
                    BluetoothManger.counter++;
                    //       GlobalVaries.UpdateWarnFlag=true;
                    Log.e("syj","update2:"+Double.toString(GlobalVaries.curBattery));

                    showWarnDialog(Integer.toString( BluetoothManger.counter), GlobalVaries.curBattery);




                    break;
                case  BluetoothManger.CLOSE_LOCK:
                    alertDialog.dismiss();
                    GlobalVaries.UpdateWarnFlag = false;
                    //syj  关锁之后立刻断开连接
                    BluetoothManger.disconnectLock();
                case BluetoothManger.UPDATE_STATE:
                    handler.postDelayed( new Runnable() {
                        @Override
                        public void run() {
                            Log.e(BluetoothManger.TAG,"RRRRRRR");
                            BluetoothManger.TMPL_SendGetLockStateCMD();

                        }
                    }, 1000);
                    break;
                case BluetoothManger.RECONNECT:
                    Log.e("syj","reconnect cunter :"+Integer.toString(ConnectCounter));
                    if(ConnectCounter==120){
                        BluetoothManger.reconnectFlag=false;
                        ConnectCounter=0;
                        ConnectCounterFlag=false;
                        BluetoothManger.disconnectLock();
                        dismissprogressDialog();
                        Toast.makeText(EmergencyDoorActivity.this,"连接设备"+GlobalVaries.curBlueMac+"失败，请检查！",Toast.LENGTH_LONG).show();
                    }else if((ConnectCounter==60)||(ConnectCounter==61)) {

                        //     BluetoothManger.connectLock(BluetoothSetActivity.this,GlobalVaries.curBlueMac,false);
                        BluetoothManger.reconnectFlag=true;
                        BluetoothManger.disconnectLock();


                    }else if((ConnectCounter==70)||(ConnectCounter==71)){
                        startBluetooth();
                        dismissprogressDialog();
                        startShowProgressDialog("正在重新连接蓝牙设备！");


                    }
//                    else if((ConnectCounter==30)||(ConnectCounter==31)){
//                        BluetoothManger.reconnectFlag=true;
//                        BluetoothManger.disconnectLock();
//
//
//                    }

                    break;

                case BluetoothManger.SEND_OPEN_RECORD:
                    sendEmergyOpenRecord(opentoken,openresaon);
                    break;

            }
        } catch (Exception ee) {
            //ee.printStackTrace();
            Log.e( BluetoothManger.TAG, ee.getMessage());
            // syj showMessage(ee.getMessage());
        }
    }


    class UpdateThread implements Runnable {
        @Override
        public void run() {
            while (GlobalVaries.UpdateWarnFlag) {
                try {
                    Thread.sleep(1000);
                    Message msg = new Message();
                    msg.what = BluetoothManger.UPDATE_WARNDIALOG;
                    handler.sendMessage(msg);
                } catch (InterruptedException e) {
// TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }


        }

    }
    class ConnectThread implements Runnable {
        @Override
        public void run() {
            while (ConnectCounterFlag) {
                try {
                    Log.e("syj","recounter "+Integer.toString(ConnectCounter));
                    Thread.sleep(1000);
                    BluetoothManger.reconnectFlag=true;
                    if(ConnectCounter==120)
                    {
                        BluetoothManger.reconnectFlag=false;
                        ConnectCounterFlag=false;
                        Message msg = new Message();
                        msg.what = BluetoothManger.RECONNECT;
                        handler.sendMessage(msg);
                    }
                    else if((ConnectCounter==60)){

                        Message msg = new Message();
                        msg.what = BluetoothManger.RECONNECT;
                        handler.sendMessage(msg);
                        ConnectCounter++;
                    }else  if((ConnectCounter==70)){

                        Message msg = new Message();
                        msg.what = BluetoothManger.RECONNECT;
                        handler.sendMessage(msg);
                        ConnectCounter++;
                    }else{
                        ConnectCounter++;
                    }
//                    Message msg = new Message();
//                    msg.what = BluetoothManger.UPDATE_WARNDIALOG;
//                    handler.sendMessage(msg);
                } catch (InterruptedException e) {
// TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }


        }
    }

}